package nju.bishe.weibo.data.db;

import java.util.ArrayList;
import java.util.List;

import weibo4android.User;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

/**
 * 关注数据库访问类。负责关注表的数据库操作
 * @author longwei.wu
 *
 */
public class FollowerDatabase {

    private static final String TAG = "DatabaseHelper";

    private static final String DATABASE_NAME = "follower_db";
    private static final int DATABASE_VERSION = 1;

    private static FollowerDatabase instance = null;
    private FollowerOpenHelper fOpenHelper = null;
    private Context mContext = null;
    
    private static class FollowerOpenHelper extends SQLiteOpenHelper{

    	public FollowerOpenHelper(Context context, String name,
                CursorFactory factory, int version) {
            super(context, name, factory, version);
        }
    	
    	public FollowerOpenHelper(Context context){
    		this(context, DATABASE_NAME, null, DATABASE_VERSION);
    	}
		@Override
		public void onCreate(SQLiteDatabase db) {
			 Log.i(TAG, "Create Database.");
			// TODO Auto-generated method stub
			db.execSQL(FollowTable.CREATE_TABLE);
		}
		
        @Override
        public synchronized void close() {
            Log.i(TAG, "Close Database.");
            super.close();
        }

        @Override
        public void onOpen(SQLiteDatabase db) {
            Log.i(TAG, "Open Database.");
            super.onOpen(db);
        }

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			 Log.i(TAG, "Upgrade Database.");
			 db.execSQL("DROP TABLE IF EXISTS " + FollowTable.TABLE_NAME);
		}
    	
    }
    
    private FollowerDatabase(Context context){
    	mContext = context;
    	fOpenHelper  = new FollowerOpenHelper(context);
    }
    
    public static synchronized FollowerDatabase getInstance(Context context){
    	 if (null == instance) {
             return new FollowerDatabase(context);
         }
         return instance;
    }
    
      public void close() {
        if (null != instance) {
            fOpenHelper.close();
            instance = null;
        }
      }
      /**
       * 获得所有的关注对象
       * @return
       */
      public List<User> fetchAllFollowers(String ownerId,int tag) {
          SQLiteDatabase mDb = fOpenHelper.getReadableDatabase();
          List<User> users = new ArrayList<User>();
          Log.i(TAG, "the owner_id is:"+ownerId);
          Cursor cursor = mDb.query(FollowTable.TABLE_NAME, FollowTable.TABLE_COLUMNS,
        		  FollowTable.FIELD_OWNER+" = ? AND "+FollowTable.FIELD_FOLLOWING+" = ?", new String[]{ownerId,tag+""}, null, null, null);
//          Cursor cursor = mDb.query(FollowTable.TABLE_NAME, FollowTable.TABLE_COLUMNS,
//        		  null, null, null, null, null);
    	  Log.i(TAG,"cursor size:"+cursor.getCount());
          if(cursor.getCount()==0){
        	  Log.i(TAG,"cursor size:"+cursor.getCount());
        	  cursor.close();
        	  return users;
          }
          cursor.moveToFirst();
          while(!cursor.isLast()){
				User user = User.MyParseUser(cursor);
				users.add(user);
				cursor.moveToNext();
          }
          cursor.close();
          
          return users;
				
		
      }
      
  
      
      /**
       * Create a follower
       * 
       * @param userId 关注对象的ID
       * @param ownerId 使用者ID
       * @return the row ID of the newly inserted row, or -1 if an error occurred
       */
      public long createFollower(User user,String ownerId,int tag) {
          SQLiteDatabase mDb = fOpenHelper.getWritableDatabase();

          ContentValues initialValues = new ContentValues();
          initialValues.put(FollowTable._ID, user.getId());
          initialValues.put(FollowTable.FIELD_CREATED_AT, user.getCreatedAt().toString());
          initialValues.put(FollowTable.FIELD_DESCRIPTION, user.getDescription());
          initialValues.put(FollowTable.FIELD_FAVORITES_COUNT, user.getFavouritesCount());
          initialValues.put(FollowTable.FIELD_FOLLOWERS_COUNT, user.getFollowersCount());
          if(tag==0){
          initialValues.put(FollowTable.FIELD_FOLLOWING, false);
          }else{
        	  initialValues.put(FollowTable.FIELD_FOLLOWING, true); 
          }
          initialValues.put(FollowTable.FIELD_PROFILE_IMAGE_URL, user.getProfileImageURL().toString());
          initialValues.put(FollowTable.FIELD_USER_SCREEN_NAME, user.getScreenName());
          initialValues.put(FollowTable.FIELD_OWNER, ownerId);
          initialValues.put(FollowTable.FIELD_FRIENDS_COUNT, user.getFriendsCount());
          initialValues.put(FollowTable.FIELD_LAST_STATUS, user.getStatusText());
          initialValues.put(FollowTable.FIELD_LOCALTION, user.getLocation());
          initialValues.put(FollowTable.FIELD_USER_NAME, user.getName());
          long rowId = mDb.insert(FollowTable.TABLE_NAME, null, initialValues);
          Log.i("Follower insert",rowId+"");
          return rowId;
      }
      /**
       * 删除所有的关注对象
       * @return
       * 		删除的条目数量
       */
      public boolean deleteAllFollowers(String ownerId,int tag) {
          SQLiteDatabase mDb = fOpenHelper.getWritableDatabase();
          int log = mDb.delete(FollowTable.TABLE_NAME, FollowTable.FIELD_OWNER+" = ? AND "+ FollowTable.FIELD_FOLLOWING+" = ?", new String[]{ownerId,tag+""});
          Log.i("Delete Follower", log+"followers has been deleted" );
          return  log > 0;
      }
      
      /**
       * 清空Followers表并添加新内容
       * 
       * @param followers
       * 			关注对象的ID
       * @param ownerId
       * 			使用者的ID
       */
      public void syncFollowers(List<User> followers,String ownerId,int tag) {
          SQLiteDatabase mDb = fOpenHelper.getWritableDatabase();

          try {
              mDb.beginTransaction();

               deleteAllFollowers(ownerId,tag);

              for (User user : followers) {
                  createFollower(user,ownerId,tag);
              }

              mDb.setTransactionSuccessful();
          } finally {
              mDb.endTransaction();
          }
      }
      
      
}
